package com.util.utillib.util.imagecovert

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.File
import java.io.IOException

object ImageConvert {

    fun startConvertImage(
        context: Context,
        file: File?,
        complete: (localPath: String?, bitmap: Bitmap?) -> Unit
    ) {
        if (file == null) return

        try {
            val folder = "${context.filesDir.absolutePath}${File.separator}ImageConvertPics"
            val imagePath = with(File(folder)) {
                if (!exists()) {
                    mkdirs()
                }
                "$absolutePath${File.separator}${System.currentTimeMillis()}.jpg"
            }

            val output = File(imagePath)
            val needCompress = ImageChecker.needCompress(300, file.absolutePath)
            val result = if (needCompress) ImageCompress(file, output, false).compress() else file

            val options = BitmapFactory.Options().apply { inJustDecodeBounds = false }
            val bitmap = BitmapFactory.decodeFile(result.absolutePath, options)

            complete.invoke(result.absolutePath, bitmap)

        } catch (e: IOException) {
            e.printStackTrace()
            complete.invoke(null, null)
        }
    }
}